// ignore_for_file: prefer_const_constructors

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:get_storage/get_storage.dart';

import 'package:multi_shop/models/address.dart';
import 'package:multi_shop/models/user.dart';
import 'package:multi_shop/services/user_api.dart';
import 'package:multi_shop/utils/index.dart';

class AddressPage extends StatefulWidget {
  const AddressPage({Key? key}) : super(key: key);

  @override
  State<AddressPage> createState() => _AddressPageState();
}

class _AddressPageState extends State<AddressPage> {
  final _api = UserApi();

  List<Address> _list = [];
  bool _loading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    // 获取用户信息
    UserInfo? user = GetStorage().read<UserInfo>('userInfo');
    debugPrint('user:$user');
    _loadList();
  }

  Future<void> _loadList() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final list = await _api.getAddressList(); // 可能为 null
      if (!mounted) return;
      setState(() {
        _list = (list ?? <Address>[]); // ← 空检测
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = e.toString();
      });
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _delete(Address a) async {
    final id = a.id;
    if (id == null) return;
    final ok = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        title: Text('确认删除？'),
        content: Text('将删除地址：${a.receiverName} ${a.receiverPhone}'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: Text('删除'),
          ),
        ],
      ),
    );
    if (ok != true) return;
    await _api.deleteAddress(id);
    if (!mounted) return;
    setState(() => _list.removeWhere((x) => x.id == id));
  }

  Future<void> _setDefault(Address a) async {
    a.isDefault = true;
    await _api.updateAddress(a);
    if (!mounted) return;
    _loadList();
  }

  void _showForm({Address? address}) {
    final formKey = GlobalKey<FormState>();

    String receiverName = address?.receiverName ?? '';
    String receiverPhone = address?.receiverPhone ?? '';
    String province = address?.province ?? '';
    String city = address?.city ?? '';
    String district = address?.district ?? '';
    String detail = address?.detailAddress ?? '';
    String postal = address?.postalCode ?? '';
    bool isDefault = address?.isDefault ?? false;

    Future<void> pickRegion() async {
      final res = await CityPickers.showCityPicker(
        context: context,
        height: 300,
        showType: ShowType.pca, // 省市区
      );
      if (res == null) return;
      province = res.provinceName ?? '';
      city = res.cityName ?? '';
      district = res.areaName ?? '';
      // 刷新底部弹窗
      (bottomSetState ?? setState)(() {});
    }

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (_) {
        return StatefulBuilder(
          builder: (ctx, setM) {
            bottomSetState = setM; // 让 pickRegion 也能局部刷新
            final bottom = MediaQuery.of(ctx).viewInsets.bottom;

            return Padding(
              padding: EdgeInsets.fromLTRB(16, 16, 16, bottom + 16),
              child: SingleChildScrollView(
                child: Form(
                  key: formKey,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(Icons.location_on, size: 20),
                          SizedBox(width: 8),
                          Text(
                            address == null ? '新增地址' : '编辑地址',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 12),

                      // 收件人
                      TextFormField(
                        initialValue: receiverName,
                        decoration: InputDecoration(
                          labelText: '收件人姓名',
                          prefixIcon: Icon(Icons.person),
                        ),
                        validator: (v) =>
                            (v == null || v.trim().isEmpty) ? '请输入收件人姓名' : null,
                        onChanged: (v) => receiverName = v.trim(),
                      ),

                      // 电话
                      TextFormField(
                        initialValue: receiverPhone,
                        decoration: InputDecoration(
                          labelText: '联系电话',
                          prefixIcon: Icon(Icons.phone),
                        ),
                        keyboardType: TextInputType.phone,
                        validator: (v) {
                          final s = v?.trim() ?? '';
                          if (s.isEmpty) return '请输入联系电话';
                          if (s.length < 6) return '手机号格式不正确';
                          return null;
                        },
                        onChanged: (v) => receiverPhone = v.trim(),
                      ),

                      // 地区（点击弹出选择器）
                      GestureDetector(
                        onTap: pickRegion,
                        child: AbsorbPointer(
                          child: TextFormField(
                            decoration: InputDecoration(
                              labelText: '所在地区',
                              prefixIcon: Icon(Icons.map),
                              suffixIcon: Icon(Icons.keyboard_arrow_right),
                            ),
                            controller: TextEditingController(
                              text: [
                                province,
                                city,
                                district,
                              ].where((e) => e.isNotEmpty).join(' '),
                            ),
                            validator: (_) {
                              if (province.isEmpty || city.isEmpty)
                                return '请选择省市区';
                              return null;
                            },
                          ),
                        ),
                      ),

                      // 详细地址
                      TextFormField(
                        initialValue: detail,
                        decoration: InputDecoration(
                          labelText: '详细地址',
                          prefixIcon: Icon(Icons.home),
                        ),
                        validator: (v) =>
                            (v == null || v.trim().isEmpty) ? '请输入详细地址' : null,
                        onChanged: (v) => detail = v.trim(),
                      ),

                      // 邮编
                      TextFormField(
                        initialValue: postal,
                        decoration: InputDecoration(
                          labelText: '邮编',
                          prefixIcon: Icon(Icons.local_post_office),
                        ),
                        keyboardType: TextInputType.number,
                        onChanged: (v) => postal = v.trim(),
                      ),

                      // 默认地址
                      InkWell(
                        splashColor: Colors.transparent, // 波纹颜色
                        highlightColor: Colors.transparent, // 高亮颜色
                        hoverColor: Colors.transparent,
                        onTap: () => setM(() => isDefault = !isDefault),
                        child: Row(
                          children: [
                            Checkbox(
                              value: isDefault,
                              onChanged: (v) =>
                                  setM(() => isDefault = v ?? false),
                            ),
                            Text('设为默认地址'),
                          ],
                        ),
                      ),
                      SizedBox(height: 12),

                      SizedBox(
                        width: double.infinity,
                        height: 44,
                        child: ElevatedButton.icon(
                          icon: Icon(Icons.save),
                          label: Text('保存'),
                          onPressed: () async {
                            if (!(formKey.currentState?.validate() ?? false))
                              return;

                            final payload = Address(
                              id: address?.id,
                              receiverName: receiverName,
                              receiverPhone: receiverPhone,
                              province: province,
                              city: city,
                              district: district,
                              detailAddress: detail,
                              postalCode: postal,
                              isDefault: isDefault,
                            );
                            if (address == null) {
                              await _api.addAddress(payload);
                              toastCenter('新增成功');
                            } else {
                              await _api.updateAddress(payload);
                              toastCenter('更新成功');
                            }
                            Get.back();
                            if (!mounted) return;
                            _loadList();
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildBody() {
    if (_loading) {
      return const Center(child: CircularProgressIndicator());
    }
    if (_error != null) {
      return Center(
        child: TextButton(
          onPressed: _loadList,
          child: Text('加载失败，点击重试\n$_error', textAlign: TextAlign.center),
        ),
      );
    }
    if (_list.isEmpty) {
      // 空态（不再显示“去新增”按钮）
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.location_off_outlined, size: 64, color: Colors.grey),
            SizedBox(height: 12),
            Text('还没有收货地址', style: TextStyle(color: Colors.grey)),
            SizedBox(height: 8),
            Text('点击右下角 “+” 新增', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadList,
      child: ListView.separated(
        physics: const AlwaysScrollableScrollPhysics(),
        itemCount: _list.length,
        separatorBuilder: (_, __) => Divider(height: 1),
        itemBuilder: (context, idx) {
          final a = _list[idx];
          return ListTile(
            leading: Icon(
              a.isDefault ? Icons.location_on : Icons.location_on_outlined,
              color: a.isDefault ? Theme.of(context).colorScheme.primary : null,
            ),
            title: Text('${a.receiverName}  ${a.receiverPhone}'),
            subtitle: Text(
              '${a.province}${a.city}${a.district} ${a.detailAddress}',
            ),
            onTap: () => Get.back(result: a), // 选择后回传
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                if (!a.isDefault)
                  TextButton(
                    onPressed: () => _setDefault(a),
                    child: Text('设为默认'),
                  ),
                IconButton(
                  icon: Icon(Icons.edit),
                  onPressed: () => _showForm(address: a),
                ),
                IconButton(
                  icon: Icon(Icons.delete_outline),
                  onPressed: () => _delete(a),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  StateSetter? bottomSetState; // 让 picker 结束后可以局部刷新

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('地址管理')),
      body: _buildBody(),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _showForm(),
        child: const Icon(Icons.add),
      ),
    );
  }
}
